package com.kasoft.emq.handler;


import com.kasoft.emq.dao.DeviceRepository;
import com.kasoft.emq.domain.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;


@Component
public class DeviceHandler {

    private final DeviceRepository deviceRepository;

	@Autowired
	MongoTemplate mongoTemplate;

    @Autowired
    public DeviceHandler(DeviceRepository deviceRepository) {
        this.deviceRepository = deviceRepository;
    }

    public void save(Device device) {
		 deviceRepository.save(device);
    }

    public Optional<Device> findDeviceById(Long id) {

        return deviceRepository.findById(id);
    }

    public Device findLastByDeviceId(String deviceId){
		Query query = new Query();
		Sort  sort = new Sort(Sort.Direction.DESC, "createDate");
		query.addCriteria(Criteria.where("deviceId").is(deviceId));
		query.with(sort).limit(1);
		return  mongoTemplate.findOne(query, Device.class);
    	//return deviceRepository.findByDeviceIdOrderByCreateDateDesc(deviceId);
	}

    public List<Device> findAllDevice() {
        return deviceRepository.findAll();
    }

    public void modifyDevice(Device device) {
		deviceRepository.save(device);
    }

    public void deleteDevice(Long id) {
		deviceRepository.deleteById(id);
    }
}
